package com.anyi.gulimall.product.service.impl;

import com.anyi.gulimall.product.entity.CategoryBrandRelationEntity;
import com.anyi.gulimall.product.service.CategoryBrandRelationService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.anyi.gulimall.common.utils.PageUtils;
import com.anyi.gulimall.common.utils.Query;

import com.anyi.gulimall.product.dao.CategoryDao;
import com.anyi.gulimall.product.entity.CategoryEntity;
import com.anyi.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 将所有分类按照树形结构返回
     * @return
     */
    @Override
    public List<CategoryEntity> listTree() {
        // 查询出所有分类信息
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);
        // 所有一级分类
        List<CategoryEntity> menus1list = categoryEntities.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(categoryEntity -> {
             categoryEntity.setChildren(this.setChildrens(categoryEntity,categoryEntities));
             return categoryEntity;
        })
                .sorted((menu1,menu2)->{
            return (menu1.getSort() ==null ? 0:menu1.getSort())- (menu2.getSort()==null?0:menu2.getSort());
        })
                .collect(Collectors.toList());

        return menus1list;
    }

    /**
     * 批量删除分类
     * @param asList
     */
    @Override
    public void deleteByIds(List<Long> asList) {
        // TODO 判断是否有关联，有关联就不删除，无关联删除
        // 查询该分类是否与品牌关联
      asList.forEach(item->{
          List<CategoryBrandRelationEntity> list = categoryBrandRelationService.list(new LambdaQueryWrapper<CategoryBrandRelationEntity>()
                  .eq(CategoryBrandRelationEntity::getCatelogId, item));
          if (list.size() == 0){
              baseMapper.deleteById(item);
          }
      });
    }

    // 更新分类
    @Transactional
    @Override
    public void updateCategoryEntity(CategoryEntity category) {

        // 更新了分类信息
        this.updateById(category);

        // TODO 同步更新其他级联信息
        // 同步更新分类与品牌关联的信息
        CategoryBrandRelationEntity categoryBrandRelationEntity = new CategoryBrandRelationEntity();
        categoryBrandRelationEntity.setCatelogId(category.getCatId());
        categoryBrandRelationEntity.setCatelogName(category.getName());
        categoryBrandRelationService.update(categoryBrandRelationEntity,
                new LambdaQueryWrapper<CategoryBrandRelationEntity>().eq(CategoryBrandRelationEntity::getCatelogId,category.getCatId()));
    }

    // 递归设置菜单的子菜单
    private List<CategoryEntity> setChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> childrens = all.stream().filter(item -> {
            return item.getParentCid() == root.getCatId();
        }).map(item -> {
            item.setChildren(setChildrens(item, all));
            return item;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() ==null ? 0:menu1.getSort())- (menu2.getSort()==null?0:menu2.getSort());
        }).collect(Collectors.toList());

        return childrens;
    }

}